


//
//  NSArray+Util.m
//  云成绩
//
//  Created by Apple1 on 2017/3/27.
//  Copyright © 2017年 zj. All rights reserved.
//

#import "NSArray+Util.h"

@implementation NSArray (Util)

- (NSInteger)find:(BOOL (^)(id))condition {
    for (NSInteger i = 0; i<self.count; i++) {
        if (condition(self[i])) return i;
    }
    return NSNotFound;
}

-(NSArray *)filter:(BOOL (^)(id))condition {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id item in self) {
        if (!condition(item)) continue;
        
        [array addObject:item];
    }
    return [array copy];
}

- (NSArray *)flatMap:(id (^)(id))condition {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id item in self) {
        id obj = condition(item);
        if (obj == nil) continue;
        
        [array addObject:obj];
    }
    return [array copy];
}

- (NSArray *)map:(id (^)(id))condition {
    NSMutableArray *array = [NSMutableArray arrayWithCapacity:self.count];
    for (id item in self) {
        id obj = condition(item);
        [array addObject:obj];
    }
    return [array copy];
}


#pragma mark - forEach
- (void)forEach:(void(^)(id))condition{
    for (id object in self) {
        condition(object);
    }
}

#pragma mark - reduce

- (id)reduce:(id __nullable)initialValue andCondition:(id (^)(id __nullable, id))condition{
    id result = initialValue;
    for (id object in self) {
        result = condition(result, object);
    }
    return result;
}

@end
